import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown
from kivy.uix.spinner import Spinner
from kivy.uix.slider import Slider
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.scrollview import ScrollView
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, StringProperty, ListProperty
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
from kivy.core.text import LabelBase
import json
import os
from pypinyin import lazy_pinyin, Style

# 注册中文字体
# Windows系统中文字体路径
font_path = "C:/Windows/Fonts/msyh.ttc"  # 微软雅黑
if os.path.exists(font_path):
    LabelBase.register(name='Chinese', fn_regular=font_path)
else:
    # 如果找不到微软雅黑，尝试其他中文字体
    font_paths = [
        "C:/Windows/Fonts/simhei.ttf",  # 黑体
        "C:/Windows/Fonts/simsun.ttc",  # 宋体
        "C:/Windows/Fonts/msyh.ttf"     # 微软雅黑另一种格式
    ]
    for path in font_paths:
        if os.path.exists(path):
            LabelBase.register(name='Chinese', fn_regular=path)
            break

kivy.require('2.0.0')

class PoetryDisplay(BoxLayout):
    # 当前行和字符索引
    current_line = NumericProperty(0)
    current_char = NumericProperty(0)
    
    def __init__(self, **kwargs):
        super(PoetryDisplay, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.padding = [20, 20, 20, 20]
        self.spacing = 10
        
        # 加载诗词数据
        self.load_poetry_data()
        
        # 当前诗词索引
        self.current_poetry_index = 0
        self.current_poetry = self.poetry_list[self.current_poetry_index]
        
        # 跟读状态
        self.is_reading = False
        self.event = None
        
        # 创建UI
        self.create_ui()
        
    def load_poetry_data(self):
        """加载诗词数据"""
        # 简化的诗词数据
        self.poetry_list = [
            {
                "title": "静夜思",
                "author": "李白",
                "dynasty": "唐",
                "content": [
                    "床前明月光",
                    "疑是地上霜",
                    "举头望明月",
                    "低头思故乡"
                ]
            },
            {
                "title": "春晓",
                "author": "孟浩然",
                "dynasty": "唐",
                "content": [
                    "春眠不觉晓",
                    "处处闻啼鸟",
                    "夜来风雨声",
                    "花落知多少"
                ]
            },
            {
                "title": "登鹳雀楼",
                "author": "王之涣",
                "dynasty": "唐",
                "content": [
                    "白日依山尽",
                    "黄河入海流",
                    "欲穷千里目",
                    "更上一层楼"
                ]
            }
        ]
        
    def create_ui(self):
        """创建用户界面"""
        # 标题区域
        title_layout = BoxLayout(size_hint=(1, 0.15), spacing=10)
        
        # 诗词选择下拉框
        self.spinner = Spinner(
            text=f"{self.current_poetry['title']} - {self.current_poetry['author']}",
            values=[f"{poem['title']} - {poem['author']}" for poem in self.poetry_list],
            size_hint=(0.4, 1),
            font_name='Chinese'
        )
        self.spinner.bind(text=self.on_poetry_selected)
        title_layout.add_widget(self.spinner)
        
        # 标题标签
        self.title_label = Label(
            text=f"{self.current_poetry['title']}",
            font_size='24sp',
            bold=True,
            font_name='Chinese'
        )
        title_layout.add_widget(self.title_label)
        
        # 作者标签
        self.author_label = Label(
            text=f"{self.current_poetry['dynasty']} · {self.current_poetry['author']}",
            font_size='18sp',
            font_name='Chinese'
        )
        title_layout.add_widget(self.author_label)
        
        self.add_widget(title_layout)
        
        # 诗词显示区域（带滚动）
        self.scroll_view = ScrollView(size_hint=(1, 0.6))
        self.poetry_layout = GridLayout(cols=1, spacing=20, size_hint_y=None)
        self.poetry_layout.bind(minimum_height=self.poetry_layout.setter('height'))
        
        self.line_labels = []
        self.pinyin_labels = []
        
        # 创建诗词行标签
        for i, line in enumerate(self.current_poetry['content']):
            # 拼音标签
            pinyin_text = " ".join(lazy_pinyin(line, style=Style.TONE))
            pinyin_label = Label(
                text=pinyin_text,
                font_size='16sp',
                color=(0.5, 0.5, 0.5, 1),
                size_hint_y=None,
                height=30,
                font_name='Chinese'
            )
            self.poetry_layout.add_widget(pinyin_label)
            self.pinyin_labels.append(pinyin_label)
            
            # 诗句标签
            line_label = Label(
                text=line,
                font_size='22sp',
                size_hint_y=None,
                height=50,
                font_name='Chinese'
            )
            self.poetry_layout.add_widget(line_label)
            self.line_labels.append(line_label)
            
        self.scroll_view.add_widget(self.poetry_layout)
        self.add_widget(self.scroll_view)
        
        # 控制面板
        control_layout = BoxLayout(size_hint=(1, 0.25), spacing=10)
        
        # 左侧按钮
        button_layout = BoxLayout(orientation='vertical', spacing=5, size_hint_x=0.6)
        
        # 开始/停止按钮
        self.start_stop_btn = Button(text='开始跟读', font_size='18sp', font_name='Chinese')
        self.start_stop_btn.bind(on_press=self.toggle_reading)
        button_layout.add_widget(self.start_stop_btn)
        
        # 速度控制
        speed_layout = BoxLayout(spacing=10)
        speed_layout.add_widget(Label(text='速度:', font_size='16sp', size_hint_x=0.3, font_name='Chinese'))
        
        self.speed_slider = Slider(min=0.5, max=2.0, value=1.0, size_hint_x=0.7)
        self.speed_slider.bind(value=self.on_speed_change)
        speed_layout.add_widget(self.speed_slider)
        
        self.speed_label = Label(text='1.0x', font_size='16sp', size_hint_x=0.2, font_name='Chinese')
        speed_layout.add_widget(self.speed_label)
        
        button_layout.add_widget(speed_layout)
        control_layout.add_widget(button_layout)
        
        # 右侧导航按钮
        nav_layout = BoxLayout(orientation='vertical', spacing=5, size_hint_x=0.4)
        
        self.prev_btn = Button(text='上一首', font_size='16sp', font_name='Chinese')
        self.prev_btn.bind(on_press=self.previous_poetry)
        nav_layout.add_widget(self.prev_btn)
        
        self.next_btn = Button(text='下一首', font_size='16sp', font_name='Chinese')
        self.next_btn.bind(on_press=self.next_poetry)
        nav_layout.add_widget(self.next_btn)
        
        control_layout.add_widget(nav_layout)
        self.add_widget(control_layout)
        
    def on_poetry_selected(self, spinner, text):
        """处理诗词选择"""
        # 根据选择的文本找到对应的诗词索引
        for i, poem in enumerate(self.poetry_list):
            if f"{poem['title']} - {poem['author']}" == text:
                self.current_poetry_index = i
                break
                
        self.update_poetry_display()
        
    def update_poetry_display(self):
        """更新诗词显示"""
        self.current_poetry = self.poetry_list[self.current_poetry_index]
        
        # 更新标题和作者
        self.title_label.text = self.current_poetry['title']
        self.author_label.text = f"{self.current_poetry['dynasty']} · {self.current_poetry['author']}"
        
        # 更新诗词内容
        for i, (line_label, pinyin_label) in enumerate(zip(self.line_labels, self.pinyin_labels)):
            if i < len(self.current_poetry['content']):
                line_label.text = self.current_poetry['content'][i]
                pinyin_text = " ".join(lazy_pinyin(self.current_poetry['content'][i], style=Style.TONE))
                pinyin_label.text = pinyin_text
            else:
                line_label.text = ""
                pinyin_label.text = ""
                
    def toggle_reading(self, instance):
        """切换跟读状态"""
        if not self.is_reading:
            self.start_reading()
        else:
            self.stop_reading()
            
    def start_reading(self):
        """开始跟读"""
        self.is_reading = True
        self.start_stop_btn.text = '停止跟读'
        
        # 重置高亮
        self.reset_highlight()
        
        # 开始跟读动画
        self.current_line = 0
        self.current_char = 0
        self.reading_step()
        
    def stop_reading(self):
        """停止跟读"""
        self.is_reading = False
        self.start_stop_btn.text = '开始跟读'
        
        # 取消定时器
        if self.event:
            self.event.cancel()
            
        # 重置高亮
        self.reset_highlight()
        
    def reading_step(self):
        """跟读步骤"""
        if not self.is_reading:
            return
            
        # 获取当前行
        if self.current_line < len(self.current_poetry['content']):
            line = self.current_poetry['content'][self.current_line]
            chars = list(line)
            
            # 如果还有字符未读完
            if self.current_char < len(chars):
                # 高亮当前字符
                self.highlight_character(self.current_line, self.current_char)
                self.current_char += 1
                
                # 根据速度设置下次调用时间
                speed = self.speed_slider.value
                delay = 0.5 / speed
                self.event = Clock.schedule_once(lambda dt: self.reading_step(), delay)
            else:
                # 行结束，移动到下一行
                self.current_line += 1
                self.current_char = 0
                
                # 如果还有下一行
                if self.current_line < len(self.current_poetry['content']):
                    # 等待一段时间后继续
                    speed = self.speed_slider.value
                    delay = 1.0 / speed
                    self.event = Clock.schedule_once(lambda dt: self.reading_step(), delay)
                else:
                    # 全部读完，停止
                    self.stop_reading()
        else:
            # 全部读完，停止
            self.stop_reading()
            
    def highlight_character(self, line_idx, char_idx):
        """高亮字符"""
        # 重置所有行的颜色
        for i, label in enumerate(self.line_labels):
            if i < len(self.current_poetry['content']):
                if i < line_idx:
                    # 已经读过的行，使用完成颜色
                    label.color = (0, 0.8, 0, 1)  # 绿色
                elif i == line_idx:
                    # 当前行，部分高亮
                    line = self.current_poetry['content'][i]
                    chars = list(line)
                    
                    # 创建带高亮的文本
                    highlighted_text = ""
                    for j, char in enumerate(chars):
                        if j <= char_idx:
                            highlighted_text += f"[color=ff0000]{char}[/color]"
                        else:
                            highlighted_text += char
                            
                    label.text = highlighted_text
                    label.markup = True
                else:
                    # 未读的行，使用默认颜色
                    label.color = (1, 1, 1, 1)  # 白色
                    label.text = self.current_poetry['content'][i]
                    label.markup = False
                    
    def reset_highlight(self):
        """重置高亮"""
        for i, label in enumerate(self.line_labels):
            if i < len(self.current_poetry['content']):
                label.color = (1, 1, 1, 1)  # 白色
                label.text = self.current_poetry['content'][i]
                label.markup = False
                
    def on_speed_change(self, instance, value):
        """处理速度变化"""
        self.speed_label.text = f"{value:.1f}x"
        
    def previous_poetry(self, instance):
        """上一首诗词"""
        if self.current_poetry_index > 0:
            self.current_poetry_index -= 1
            self.spinner.text = f"{self.poetry_list[self.current_poetry_index]['title']} - {self.poetry_list[self.current_poetry_index]['author']}"
            self.update_poetry_display()
            
    def next_poetry(self, instance):
        """下一首诗词"""
        if self.current_poetry_index < len(self.poetry_list) - 1:
            self.current_poetry_index += 1
            self.spinner.text = f"{self.poetry_list[self.current_poetry_index]['title']} - {self.poetry_list[self.current_poetry_index]['author']}"
            self.update_poetry_display()

class PoetryReaderApp(App):
    def build(self):
        self.title = '古诗词跟读器 - Kivy版'
        return PoetryDisplay()

if __name__ == '__main__':
    PoetryReaderApp().run()